//
//  BGAuctionAddTableViewController.m
//  bigMall
//
//  Created by LTOVE on 16/10/11.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGAuctionAddTableViewController.h"
#import "BGAuctipnAddTableViewCell.h"
#import "BGDateResult.h"
#import "BGBeforeAuctionModel.h"
#import "BGAuctionAddCellModel.h"
#import "BGCalculateMarginModel.h"
#import "LTOVEDynamicCreakButton.h"
#import "MJExtension.h"
#import "BGAddAuctionLogModel.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"
#import "BGUserInfoResult.h"
#import "BGUserInfoMode.h"
//#import "BGAuctionAddPriceControllerAddBtnParam.h"
@interface BGAuctionAddPriceControllerAddBtnParam : NSObject
@property (nonatomic,copy)NSString *auctionId;
@property (nonatomic,copy)NSString *payPassword;
@property (nonatomic,copy)NSString *margin;
@property (nonatomic,copy)NSString *price;

@end
//@implementation BGAuctionAddPriceControllerAddBtnParam
//
//
//
//@end

@interface BGAuctionAddTableViewController ()<BGAuctipnAddTableViewCellDelegate,dynamicButtonDelegate>{
    
    NSMutableArray *dataArray;
    BOOL ispop;
    BOOL isMagins;
}
@property (nonatomic,copy)NSString *auctionId;
@property (nonatomic,copy)NSString *payPassword;
@property (nonatomic,copy)NSString *margin;
@property (nonatomic,copy)NSString *price;
@property (nonatomic,strong)BGAuctionAddPriceControllerAddBtnParam *param;
@end

@implementation BGAuctionAddTableViewController

- (void)textFildChanged:(NSString *)textFildValue
{
    [self calculateMaginWithMoney:textFildValue];
    self.param.price = textFildValue;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.tableView endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
//    [self initSourceDataWithValue:nil];
    //    [self.view addSubview:view];
}

- (void)viewWillAppear:(BOOL)animated
{
    NSDictionary *dic = @{
                          NSFontAttributeName:Font34,
                          NSForegroundColorAttributeName:lightwhite_
                          };
    CGFloat btnH = 60;
    LTOVEDynamicCreakButton *view = [LTOVEDynamicCreakButton buttonViewWithFrame:CGRectMake(0, screenH - btnH, screenW, btnH) titleDataArray:@[@"出价"] andEdgInset:UIEdgeInsetsMake(5, 10, 5, 10) andMaginX:0 andMaginY:0 andBtnHeigh:btnH - 10 andBtnNorColor:read_ andBtnHeighColor:read_ andRadius:5 andFont:dic];
    view.delegate = self;
    //    self.tableView.scrollEnabled = NO;
    [BGKeyWindow addSubview:view];

}

- (void)viewWillDisappear:(BOOL)animated
{
    for (LTOVEDynamicCreakButton *view in BGKeyWindow.subviews) {
        if ([view isKindOfClass:[LTOVEDynamicCreakButton class]]) {
            [view removeFromSuperview];
        }
    }
}
- (BGAuctionAddPriceControllerAddBtnParam *)param
{
    if (!_param) {
        _param = [BGAuctionAddPriceControllerAddBtnParam new];
        _param.auctionId = self.isMagin;
    }
    return _param;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setIsMagin:(NSString *)isMagin
{
    _isMagin = isMagin;
    [self loadMessage];
}


- (void)loadMessage
{
    [BGDateResult beforeAuctionWithAuctionId:self.isMagin success:^(NSObject *result) {
        
        BGBeforeAuctionModel *model = (BGBeforeAuctionModel *)result;
        NSMutableArray *array = [NSMutableArray array];
        if ([model.is_margin isEqualToString:@"0"]) {
            isMagins = NO;
        }else{
            isMagins = YES;
        }
        [array addObject:model.max_amoutn];
        [array addObject:model.least_add];
        [array addObject:@""];
        [array addObject:model.this_price];
        [self initSourceDataWithValue:array];
        self.param.price = model.this_price;
        if (isMagins && dataArray.count == 4) {
            [dataArray removeObjectAtIndex:2];
        }
        [self.tableView reloadData];
        [self calculateMaginWithMoney:model.this_price];
        
    } failure:^(NSError *error) {
        
    }];
}


- (void)calculateMaginWithMoney:(NSString *)money
{
    if (isMagins) {
        return;
    }
    [BGDateResult calculateMarginWithRole:@"buyer" type:@"auction" money:money objId:self.isMagin success:^(NSObject *result) {
        
        BGCalculateMarginModel *model = (BGCalculateMarginModel *)result;
        //        self.resultModel.magin = model.margin;
//        self.magin = model.margin;
        BGAuctionAddCellModel *maginModel = [BGAuctionAddCellModel new];
        maginModel.title = [NSString stringWithFormat:@"保证金:%@元",model.margin];
        self.param.margin = model.margin;
        [dataArray replaceObjectAtIndex:2 withObject:maginModel];
        
        
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSError *error) {
        
        
    }];
}


- (void)initSourceDataWithValue:(NSArray *)valueArray
{
    //当前报价[NSString stringWithFormat:@"最低加价金额:%@元",valueArray[0]];
    BGAuctionAddCellModel *NowPriceModel = [BGAuctionAddCellModel new];
    NowPriceModel.title = [NSString stringWithFormat:@"当前报价:%@元",valueArray[0]];
    dataArray = [NSMutableArray array];
    [dataArray addObject:NowPriceModel];
    //最低加价金额
    BGAuctionAddCellModel *listAddModel = [BGAuctionAddCellModel new];
    listAddModel.title = [NSString stringWithFormat:@"最低加价金额:%@元",valueArray[1]];
    [dataArray addObject:listAddModel];
    //保证金
    BGAuctionAddCellModel *maginModel = [BGAuctionAddCellModel new];
    maginModel.title = [NSString stringWithFormat:@"保证金:%@元",valueArray[2]];
    [dataArray addObject:maginModel];
    //出价金额
    BGAuctionAddCellModelTextFild *priceModel = [BGAuctionAddCellModelTextFild new];
    priceModel.title = @"出价金额";
    priceModel.textFildValue = valueArray[3];
    [dataArray addObject:priceModel];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BGAuctipnAddTableViewCell *cell = [BGAuctipnAddTableViewCell cellWithTableView:tableView];
    BGAuctionAddCellModel *model = dataArray[indexPath.row];
    cell.model = model;
    cell.delegate = self;
    return cell;
}

#pragma mark - 出价按钮
- (void)dynamicButtonClick:(UIButton *)btn
{
    GWLog(@"%@",btn.titleLabel.text);
    
    GWLog(@"%@",self.param.keyValues);
    if (isMagins) {
        [self requestAddPriceApi];
    }else{
        [MBProgressHUD showMessage:nil];
        [BGDateResult getUserInfoSuccess:^(NSString *status, NSString *msg, NSDictionary *res) {
            [MBProgressHUD hideHUD];
//            BGUserInfoMode *model =(BGUserInfoMode *)res;
//            NSDictionary *modelDic = (NSDictionary *)res;
//            BGUserInfoMode *itemModel =self.param.price
            
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"当前余额:%@元;所需保证金:%@元",res[@"cash"],self.param.price] preferredStyle:UIAlertControllerStyleAlert];
            [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                
                textField.placeholder = @"请输入支付密码";
                textField.secureTextEntry = YES;
            }];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                UITextField *textFild = [alertVc.textFields firstObject];
                self.param.payPassword = textFild.text;
                GWLog(@"%@",self.param.keyValues);
#pragma mark - 这里请求出价接口
                
                [self requestAddPriceApi];
            }];
            [alertVc addAction:sure];
            [self presentViewController:alertVc animated:YES completion:^{
                
                
            }];
            
            
            
        } failure:^(NSError *error) {
            
            
        }];
        
       
    }
    
}
#pragma mark - 这里请求出价接口
/**
 *  请求出价接口
 */
- (void)requestAddPriceApi
{
    CGFloat priveValue = [self.param.price floatValue];
    self.param.price = [NSString stringWithFormat:@"%.2f",priveValue];
    [BGDateResult addAuctionLogWithAuvtionId:self.param.keyValues success:^(NSObject *result) {
        BGAddAuctionLogModel *model = (BGAddAuctionLogModel *)result;
        GWLog(@"%@",model.msg);
        [self alertViewWithMessage:model.msg status:model.status];
    } failure:^(NSError *error) {
        
    }];
}

- (void)alertViewWithMessage:(NSString *)message status:(NSString *)status
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if ([status isEqualToString:@"1"]) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    }];
    [alertVc addAction:sure];
    [self presentViewController:alertVc animated:YES completion:nil];
}


@end
